package com.xqb.listen.ui.music.mvi

import androidx.lifecycle.viewModelScope
import com.xqb.listen.IApp
import com.xqb.listen.base.IUiEvent
import com.xqb.listen.base.IViewModel
import com.xqb.listen.manager.MediaPlayManager
import com.xqb.listen.manager.media.impl.LocalMediaFinderImp
import com.xqb.listen.manager.media.model.AlbumType
import com.xqb.listen.manager.media.model.MediaModel
import com.xqb.listen.manager.permission.PermissionUtil
import com.xqb.listen.manager.permission.model.MediaType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * @author Ling
 * @date :2025/1/23 10:11
 */
class LocalMusicViewModel : IViewModel<LocalMusicIntent , LocalMusicState , IUiEvent>() {

    override fun initUiState() = LocalMusicState(PermissionUtil.hasMediaPermission(IApp.mContext , MediaType.AUDIO))

    override fun handleIntent(intent: LocalMusicIntent) {
        when(intent){
            is LocalMusicIntent.GetLocalMusic-> getAudioData()
            is LocalMusicIntent.PlayMusic-> playAudio(intent.mediaModel)
        }
    }

    private fun playAudio(mediaModel: MediaModel) {
        MediaPlayManager.singleInstance.initAudio(IApp.mContext , true , mediaModel)
    }

    private fun getAudioData() {
        if(!uiState.value.hasPermission){
            updateUiState { copy(hasPermission = true) }
        }
        viewModelScope.launch {
            val data = withContext(Dispatchers.IO){
                return@withContext LocalMediaFinderImp.getSingleInstance().getMedia(IApp.mContext , AlbumType.AUDIO)
            }
            if(!data.isNullOrEmpty()){
                uiState.value.audioList.addAll(data)
            }
        }
    }
}